/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.android.apps.mytracks.services.sensors.ant;

import static com.google.android.apps.mytracks.Constants.TAG;

import com.google.android.apps.mytracks.services.TrackRecordingService;

import android.content.Context;
import android.util.Log;

/**
 * This class manages pairing with a new sensor.  It may not be used while the
 * {@link TrackRecordingService} is active.
 *
 * @author Matthew Simmons
 */
public class AntPairer {
  public interface PairingListener {
    void foundDevice(short deviceNumber);
  }

  private final Context context;
  private final AntSensor sensor;
  private AntPairerSensorManager sensorManager;

  /**
   * @param context the context to be used when initializing the sensor manager
   * @param sensor the type of sensor with which we should pair
   */
  public AntPairer(Context context, AntSensor sensor) {
    this.context = context;
    this.sensor = sensor;
  }

  /**
   * Begins the pairing operation.  Note that only one pairing operation may
   * be active at any given time.  {@link #stopPairing} must be called before
   * an additional pairing operation may begin.  Pairing is performed
   * asynchronously, with completion signaled by the invocation of the
   * listener.
   *
   * @param pairingListener invoked when a sensor is found
   */
  public void startPairing(PairingListener pairingListener) {
    if (sensorManager != null) {
      Log.e(TAG, "Pairing has already been started; ignoring this request");
      return;
    }

    sensorManager = new AntPairerSensorManager(context, sensor, pairingListener);
    sensorManager.setupChannel();
  }

  /**
   * Stop or cancel an outstanding pairing operation.  This method may be
   * called from inside a {@link PairingListener#foundDevice} call.  The
   * pairing listener registered by a previous call to {@link #startPairing}
   * will not be called after this method returns.
   */
  public void stopPairing() {
    if (sensorManager != null) {
      sensorManager.onDestroy();
      sensorManager = null;
    }
  }
}
